<script setup lang="ts">
import { reqGetRuleList, reqDeleteRule, reqAddRule, reqUpdateRule, reqUpdateRuleStatus } from '@/api/rule'
import { useInitTable, useInitForm } from '@/composables/useCommon'

const roles = ref([])
const defaultExpandedKeys = ref([]) // 默认 展开的节点， 需要有node-key
const { tableData, loading, getData, handleDelete, handleStatusChange } = useInitTable({
  getList: reqGetRuleList,
  delete: reqDeleteRule,
  updateStatus: reqUpdateRuleStatus,
  onGetListSuccess: (res: any) => {
    roles.value = res.data.rules
    tableData.value = res.data.list
    defaultExpandedKeys.value = res.data.list.map((item: any) => item.id)
  }
})

const { formDrawerRef, formRef, drawerTitle, form, rules, handleSubmit, handleAdd, handleEdit } = useInitForm({
  getData,
  initialForm: {
    rule_id: 0, // 父级id
    menu: 1, // 菜单 1 权限 0
    name: '', // 菜单/权限名称
    condition: '', // 后端规则,（menu为0时必填）
    method: 'GET', // 请求方式（menu为0时必填）
    status: 1, //是否启用
    order: 50, // 排序
    icon: '', // 图标 （menu为1必填）
    frontpath: '' // 对应前端路由路径（menu为1且rule_id>0时必填）
  },
  rules: {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
  },
  update: reqUpdateRule,
  create: reqAddRule
})

const defaultProps = { label: 'name', children: 'child' }
// 增加子节点
const addChild = (id: number) => {
  handleAdd()
  form.rule_id = id
  form.status = 1
}
const handleNodeClick = (data: any, node: any, component: any) => {
  // console.log(data, node, component)
}
</script>

<template>
  <div>
    <el-card shadow="never" style="border: 0; margin: 10px">
      <ListHeader @refresh="getData" @create="handleAdd" />
      <el-tree
        :data="tableData"
        :props="defaultProps"
        node-key="id"
        :default-expanded-keys="defaultExpandedKeys"
        highlight-current
        @node-click="handleNodeClick"
        v-loading="loading"
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <el-tag size="small" :type="data.menu ? 'primary' : 'info'">
              {{ data.menu ? '菜单' : '权限' }}
            </el-tag>
            <el-icon v-if="data.icon" :size="16" style="margin: 0 8px">
              <component :is="data.icon" />
            </el-icon>
            <span>{{ node.label }}</span>
            <div class="btn" @click.stop="">
              <el-switch
                :modelValue="data.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(data, data.status)"
              />
              <el-button size="small" text type="primary" icon="edit" @click.stop="handleEdit(data)">编辑</el-button>
              <el-button size="small" text type="success" icon="plus" @click.stop="addChild(data.id)">增加</el-button>
              <el-popconfirm title="是否确认要删除吗?" width @confirm="handleDelete(data.id)">
                <template #reference>
                  <el-button size="small" text type="danger" icon="delete">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </div>
        </template>
      </el-tree>
      <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" :inline="false">
          <el-form-item label="上级菜单" prop="rule_id">
            <el-cascader
              v-model="form.rule_id"
              :options="roles"
              :props="{
                label: 'name',
                children: 'child',
                value: 'id',
                checkStrictly: true,
                emitPath: false
              }"
              placeholder="请选择上级菜单"
            />
          </el-form-item>
          <el-form-item label="是否是菜单" prop="menu">
            <el-radio-group v-model="form.menu">
              <el-radio :value="1" border>菜单</el-radio>
              <el-radio :value="0" border>规则</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="菜单规则名称" style="width: 30%"></el-input>
          </el-form-item>
          <el-form-item label="图标" prop="icon" v-if="form.menu == 1">
            <IconSelect v-model="form.icon"></IconSelect>
          </el-form-item>
          <el-form-item label="前端路由路径" prop="frontpath" v-if="form.menu == 1 && form.rule_id > 0">
            <el-input v-model="form.frontpath"></el-input>
          </el-form-item>
          <el-form-item label="后端规则" prop="condition" v-if="form.menu == 0">
            <el-input v-model="form.condition"></el-input>
          </el-form-item>
          <el-form-item label="请求方式" prop="method" v-if="form.menu == 0">
            <el-select v-model="form.method" placeholder="选择请求方式" style="width: 30%" v-if="form.menu == 0">
              <el-option v-for="item in ['GET', 'POST', 'PUT', 'DELETE']" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="排序" prop="order">
            <el-input-number v-model="form.order" :min="0" :max="999" />
          </el-form-item>
          <el-form-item label="是否启用" prop="status">
            <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-form>
      </FormDrawer>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 20px;
  .btn {
    margin-left: auto;
  }
}
:deep(.el-tree-node__content) {
  padding: 20px;
}
</style>
